package com.carnation.servlet;

import java.io.IOException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.carnation.service.FileService;
import com.carnation.service.impl.FileServiceImpl;
import com.carnation.utils.Json;
import com.carnation.utils.SessionInfo;
import com.google.gson.Gson;

public class DeleteFileServlet extends HttpServlet{

	private static final long serialVersionUID = 1L;
	
	@Override
	protected void doPost(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse) throws IOException{
		Json json = new Json();
		String msg = null;
		String status = null;
		String filename = httpServletRequest.getParameter("name");
		String catalogId = httpServletRequest.getParameter("catalogId");
		SessionInfo sessionInfo = (SessionInfo)httpServletRequest.getSession().getAttribute("sessionInfo");
		if(!sessionInfo.getUser().getRole().equals("manager")){
			msg = "您没有权限删除文件";
			status = "400";
		}
		else{
			if(filename == null || filename.isEmpty() || catalogId == null || catalogId.isEmpty()){
				msg = "传入的参数有误,请联系系统管理员";
				status = "400";
			}
			else{
				FileService fileService = new FileServiceImpl();
				if(fileService.deleteFile(catalogId, filename)){
					msg = "删除文件成功";
					status = "200";
				}
				else{
					msg = "在删除文件时发生错误,请联系管理员";
					status = "400";
				}
			}
		}
		json.setMsg(msg);
		json.setStatus(status);
		Gson g= new Gson();
		httpServletResponse.setCharacterEncoding("UTF-8");
		httpServletResponse.getWriter().write(g.toJson(json));
		httpServletResponse.getWriter().close();

	}
	
	@Override
	protected void doGet(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse) throws IOException{
		doPost(httpServletRequest, httpServletResponse);
	}
}
